<template>
  <div class="update-avator">
    <!-- src 可识别的数据： 路径 外部链接， base64-->
    <img :src="photo" class="img" ref="image" />

    <footer>
      <span @click="$parent.$parent.isShowAvator = false">取消</span>
      <span @click="uploadAvator">完成</span>
    </footer>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { uploadAvatorAPI } from '@/api'
export default {
  props: {
    photo: {
      type: String,
      required: true
    }
  },
  mounted() {
    // 挂载完毕获取节点  但只能获取当前一次  在父盒子中控制这个组件的动态创建销毁可解决选择图片后页面不变化的bug
    this.init()
  },
  methods: {
    init() {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: 'none',
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      })
    },
    uploadAvator() {
      // 1.拿到裁剪后的头像
      this.myCropper.getCroppedCanvas().toBlob(async (blob) => {
        // 加载提示
        this.$toast.loading({
          message: '图片正在上传…',
          forbidClick: true
        })

        // 2.发送请求 修改服务器的头像
        try {
          const {
            data: { data }
          } = await uploadAvatorAPI(blob)
          // console.log(data)
          // 3.渲染页面  通知父组件改页面的头像
          this.$emit('update-avator', data.photo)
          this.$toast.success('图片上传成功')
        } catch (error) {
          this.$toast.fail('图片上传失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avator {
  height: 100%;
  position: relative;

  .img {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    width: 100%;
    height: 65%;
  }

  footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    color: #fff;
    font-size: 40px;
  }
}
</style>
